package io.github.harmonly.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;

public class JSONUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    public static String result(boolean success) {
        ObjectNode json = mapper.createObjectNode();
        json.put("success", success);
        return json.toString();
    }

    public static String toJSONString(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return result(false);
        }
    }

    public static <T> T parseObject(String content, Class<T> type) {
        try {
            return mapper.readValue(content, type);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
